<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作品方向" prop="workDirection">
        <el-select v-model="queryParams.workDirection" placeholder="请选择作品方向" clearable>
          <el-option
            v-for="dict in direction"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类别ID" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入类别ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="小说名" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入小说名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作家ID" prop="authorId">
        <el-input
          v-model="queryParams.authorId"
          placeholder="请输入作家ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入评分"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书籍状态" prop="bookStatus">
        <el-select v-model="queryParams.bookStatus" placeholder="请选择书籍状态" clearable>
          <el-option
            v-for="dict in book_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['novel:bookInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['novel:bookInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['novel:bookInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['novel:bookInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="作品方向" align="center" prop="workDirection">
        <template #default="scope">
          <dict-tag :options="direction" :value="scope.row.workDirection"/>
        </template>
      </el-table-column>
      <el-table-column label="类别ID" align="center" prop="categoryId" />
      <el-table-column label="小说封面地址" align="center" prop="picUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.picUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="小说名" align="center" prop="bookName" />
      <el-table-column label="作家ID" align="center" prop="authorId" />
      <el-table-column label="书籍描述" align="center" prop="bookDesc" />
      <el-table-column label="评分" align="center" prop="score" />
      <el-table-column label="书籍状态" align="center" prop="bookStatus">
        <template #default="scope">
          <dict-tag :options="book_status" :value="scope.row.bookStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="点击量" align="center" prop="visitCount" />
      <el-table-column label="总字数" align="center" prop="wordCount" />
      <el-table-column label="评论数" align="center" prop="commentCount" />
      <el-table-column label="最新章节ID" align="center" prop="lastChapterId" />
      <el-table-column label="最新章节名" align="center" prop="lastChapterName" />
      <el-table-column label="最新章节更新时间" align="center" prop="lastChapterUpdateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastChapterUpdateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['novel:bookInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['novel:bookInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小说列表对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bookInfoRef" :model="form" :rules="rules" :inline="true" label-width="90px">
        <el-form-item label="作品方向" prop="workDirection">
          <el-select v-model="form.workDirection" placeholder="请选择作品方向">
            <el-option
              v-for="dict in direction"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入类别" />
        </el-form-item>
        <el-form-item label="小说名" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入小说名" />
        </el-form-item>
        <el-form-item label="作家" prop="authorId">
          <el-input v-model="form.authorId" placeholder="请输入作家" />
        </el-form-item>
        <el-form-item label="小说封面" prop="picUrl">
          <image-upload v-model="form.picUrl"/>
        </el-form-item>
        <el-form-item label="书籍描述">
          <editor v-model="form.bookDesc" :min-height="192"/>
        </el-form-item>
        <el-divider content-position="center">小说章节信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddBookChapter">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteBookChapter">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bookChapterList" :row-class-name="rowBookChapterIndex" @selection-change="handleBookChapterSelectionChange" ref="bookChapter">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="章节号" prop="chapterNum" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.chapterNum" placeholder="请输入章节号" />
            </template>
          </el-table-column>
          <el-table-column label="章节名" prop="chapterName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.chapterName" placeholder="请输入章节名" />
            </template>
          </el-table-column>
          <el-table-column label="章节字数" prop="wordCount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.wordCount" placeholder="请输入章节字数" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BookInfo">
import { listBookInfo, getBookInfo, delBookInfo, addBookInfo, updateBookInfo } from "@/api/novel/bookInfo";

const { proxy } = getCurrentInstance();
const { direction, book_status } = proxy.useDict('direction', 'book_status');

const bookInfoList = ref([]);
const bookChapterList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedBookChapter = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeLastChapterUpdateTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workDirection: null,
    categoryId: null,
    bookName: null,
    authorId: null,
    score: null,
    bookStatus: null,
    lastChapterUpdateTime: null,
  },
  rules: {
    workDirection: [
      { required: true, message: "作品方向不能为空", trigger: "change" }
    ],
    categoryId: [
      { required: true, message: "类别ID不能为空", trigger: "blur" }
    ],
    picUrl: [
      { required: true, message: "小说封面地址不能为空", trigger: "blur" }
    ],
    bookName: [
      { required: true, message: "小说名不能为空", trigger: "blur" }
    ],
    authorId: [
      { required: true, message: "作家ID不能为空", trigger: "blur" }
    ],
    bookDesc: [
      { required: true, message: "书籍描述不能为空", trigger: "blur" }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询小说列表列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeLastChapterUpdateTime && '' != daterangeLastChapterUpdateTime) {
    queryParams.value.params["beginLastChapterUpdateTime"] = daterangeLastChapterUpdateTime.value[0];
    queryParams.value.params["endLastChapterUpdateTime"] = daterangeLastChapterUpdateTime.value[1];
  }
  listBookInfo(queryParams.value).then(response => {
    bookInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    workDirection: null,
    categoryId: null,
    picUrl: null,
    bookName: null,
    authorId: null,
    bookDesc: null,
    score: null,
    bookStatus: null,
    visitCount: null,
    wordCount: null,
    commentCount: null,
    lastChapterId: null,
    lastChapterName: null,
    lastChapterUpdateTime: null,
    createTime: null,
    updateTime: null
  };
  bookChapterList.value = [];
  proxy.resetForm("bookInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeLastChapterUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加小说";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBookInfo(_id).then(response => {
    form.value = response.data;
    bookChapterList.value = response.data.bookChapterList;
    open.value = true;
    title.value = "修改小说";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bookInfoRef"].validate(valid => {
    if (valid) {
      form.value.bookChapterList = bookChapterList.value;
      if (form.value.id != null) {
        updateBookInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBookInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除小说列表编号为"' + _ids + '"的数据项？').then(function() {
    return delBookInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 小说章节序号 */
function rowBookChapterIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 小说章节添加按钮操作 */
function handleAddBookChapter() {
  let obj = {};
  obj.chapterNum = "";
  obj.chapterName = "";
  obj.wordCount = "";
  bookChapterList.value.push(obj);
}

/** 小说章节删除按钮操作 */
function handleDeleteBookChapter() {
  if (checkedBookChapter.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的小说章节数据");
  } else {
    const bookChapters = bookChapterList.value;
    const checkedBookChapters = checkedBookChapter.value;
    bookChapterList.value = bookChapters.filter(function(item) {
      return checkedBookChapters.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleBookChapterSelectionChange(selection) {
  checkedBookChapter.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('novel/bookInfo/export', {
    ...queryParams.value
  }, `bookInfo_${new Date().getTime()}.xlsx`)
}

getList();
</script>
